import React, { memo, useRef, useEffect } from "react";
import { DragWrap } from "./style";

export default memo(function Drag(props) {
  const tipsRef = useRef();

  const mouseDown = (e) => {
    e.preventDefault();
    const pageX = e.pageX;
    const pageY = e.pageY;
    const tipX = tipsRef.current.offsetLeft;
    const tipY = tipsRef.current.offsetTop;
    const scrolltopTemp =
      document.documentElement.scrollTop || document.body.scrollTop;

    document.onmousemove = (e) => {
      e.preventDefault();
      const xx = tipX + e.clientX - pageX;
      const yy = tipY + e.clientY - pageY;
      tipsRef.current.style.transform = "none";
      tipsRef.current.style.left = xx + "px";
      tipsRef.current.style.top = yy + "px";
      if (xx < 0) {
        tipsRef.current.style.left = "0px";
      }
      if (yy < 0) {
        tipsRef.current.style.top = "0px";
      }
      if (xx > document.body.clientWidth - 480) {
        tipsRef.current.style.left = document.body.clientWidth - 480 + "px";
      }
      if (scrolltopTemp > 0) {
        if (yy + scrolltopTemp > 2501) {
          tipsRef.current.style.top = "2501px";
          return;
        }
        tipsRef.current.style.top = scrolltopTemp + yy + "px";
      }
    };
  };
  const mouseUp = (e) => {
    e.preventDefault();
    document.onmousemove = null;
  };

  const closeTips = () => {
    tipsRef.current.style.display = "none";
    props.close(0);
  };

  const btnC = () => {
    tipsRef.current.style.display = "none";
    props.close(0);
  };

  useEffect(() => {
    if (props.kg === 1) {
      tipsRef.current.style.display = "block";
      tipsRef.current.style.left = props.pleft + "px";
      tipsRef.current.style.top = props.ptop + "px";
    }
  }, [props.kg, props.ptop, props.pleft]);

  return (
    <DragWrap
      pleft={props.pleft}
      ptop={props.ptop}
      pos={props.kg}
      ref={tipsRef}
    >
      <div className="tips">
        <div
          onMouseDown={(e) => mouseDown(e)}
          onMouseUp={(e) => mouseUp(e)}
          className="tipsBox"
        >
          提示
          <i onClick={closeTips} className="closeBtn"></i>
        </div>
        <div className="tips-text">
          <span>由于版权保护，您所在的地区暂时无法使用。</span>
          <div>
            <a onClick={btnC} className="btn button2">
              <i className="button2">知道了</i>
            </a>
          </div>
        </div>
      </div>
    </DragWrap>
  );
});
